package com.qjq.glasses_shopping.redis;


import com.qjq.glasses_shopping.pojo.Orders;
import com.qjq.glasses_shopping.pojo.SeckillGoods;
import com.qjq.glasses_shopping.service.OrdersService;
import com.qjq.glasses_shopping.service.SeckillService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

/**
 * redis监听类继承KeyExpirationEventMessageListener
 */
@Component
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private SeckillService seckillService;
    @Autowired
    private OrdersService ordersService;



    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    /**
     * 订单过期后，交易关闭，回退商品库存
     */
    @Override
    public void onMessage(Message message, byte[] pattern) {
        // 获取失效key，即订单id
        String expiredKey = message.toString();
        // 拿到复制秒杀订单信息
        Orders order = (Orders) redisTemplate.opsForValue().get(expiredKey + "_copy");
        if (order != null) {
            Long goodId = order.getCartGoods().get(0).getGoodId();// 产品id
            Integer num = order.getCartGoods().get(0).getNum();// 产品数量
            // 查询秒杀商品
            SeckillGoods seckillGoods = seckillService.findSeckillGoodsByRedis(goodId);
            ordersService.findById(order.getId());
            if (order.getStatus() == 1){
                // 如果此时订单状态还是未支付，则将状态改为交易关闭
                order.setStatus(6);
                ordersService.update(order);
            }
            // 回退库存
            seckillGoods.setStockCount(seckillGoods.getStockCount() + num);
            redisTemplate.boundHashOps("seckillGoods").put(goodId,seckillGoods);
            // 删除复制订单数据
            redisTemplate.delete(expiredKey+"_copy");

        }else {
            // 处理普通订单过期
            // 查询普通订单
            Orders orders = (Orders) redisTemplate.opsForValue().get(expiredKey + "_copy1");
            // 如果此时订单状态还是未支付，则将状态改为交易关闭
            if (orders.getStatus() == 1){
                orders.setStatus(6);
                ordersService.update(orders);
            }
            // 删除复制订单数据
            redisTemplate.delete(expiredKey+"_copy1");
        }

    }
}
